import { useEffect } from 'react'
import { Result, Form, Input, Button } from 'antd'

import Layout from '../components/layout'
import { RESET_SIGNUP, SignupPayload } from '../store/actions/auth'
import { useDispatch, useSelector } from 'react-redux'
import { AppState } from '../store/reducers'
import { AuthState } from '../store/reducers/auth'
import { Link } from 'react-router-dom'

const Signup = () => {
  const dispatch = useDispatch()

  const indent = 3

  // 发送注册请求
  function onFinish(payload: SignupPayload) {
    dispatch({ type: 'SIGNUP', payload })
  }
  
  // 获取注册结果
  const auth = useSelector<AppState, AuthState>(state => state.auth)

  // 显示注册结果
  function showResult() {
    if (auth.signup.loaded) {
      return auth.signup.success ? (
        <Result
          status='success'
          title='注册成功'
          extra={[
            <Button type='primary' key='signin'>
              <Link to='/signin'>登录</Link>
            </Button>,
          ]}
        />
      ) : (
        <Result status='error' title={auth.signup.message} />
      )
    }
  }

  // 重置表单
  const [form] = Form.useForm()
  useEffect(() => {
    auth.signup.success && auth.signup.loaded && form.resetFields()
  }, [auth, form])

  // 重置状态
  useEffect(() => {
    dispatch({ type: RESET_SIGNUP })
  }, [dispatch])

  //
  return (
    <Layout title='注册' subTitle='注册一个试试'>
      {showResult()}
      <Form
        form={form}
        labelCol={{
          span: indent,
        }}
        onFinish={onFinish}
      >
        <Form.Item
          label='名字'
          name='name'
          rules={[
            {
              required: true,
              message: 'Please input your name!',
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label='邮箱'
          name='email'
          rules={[
            {
              required: true,
              message: 'Please input your email!',
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label='密码'
          name='password'
          rules={[
            {
              required: true,
              message: 'Please input your password!',
            },
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          wrapperCol={{
            offset: indent,
          }}
        >
          <Button type='primary' htmlType='submit'>
            注册
          </Button>
        </Form.Item>
      </Form>
    </Layout>
  )
}

export default Signup
